﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class VariableStepSize : MonoBehaviour {

	public InputField aInputField;
	public InputField bInputField;
	public InputField eInputField;
	public Button ConfirmButton;
	public Button nextStepButton;
	public Text tText;
	public Text answerText;

	private float a;
	private float b;
	private float e;
	private float h;
	private float T0;
	private float T1;
	private float t;
	private int n;

	private List<Vector2> pointList = new List<Vector2>();
	public DrawTrapezoids drawTrapezoids;

	// Start is called before the first frame update
	void Start() {
		n = 1;
	}

	// Update is called once per frame
	void Update() {

	}

	public void ConfirmData() {
		GetData();
		h = b - a;
		T0 = h * (F(a) + F(b)) / 2f;
		T1 = T0 / 2f + h * F(a + h / 2) / 2f;
		n = 1;
		//MarkPoints();
		ConfirmButton.interactable = false;
		nextStepButton.interactable = true;
	}

	public void OneStep() {
		Calculate();
		MarkPoints();
	}

	private void MarkPoints() {
		pointList.Clear();
		pointList.Add(new Vector2(a, F(a)));
		for (int i = 1; i < n; i++) {
			float x = a + (i - 0.5f) * h;
			float y = F(x);
			pointList.Add(new Vector2(x, y));
		}
		pointList.Add(new Vector2(b, F(b)));
		drawTrapezoids.pointList = pointList;
		drawTrapezoids.UpdateLine();
	}

	private void Calculate() {
		t = Mathf.Abs(T1 - T0);
		tText.text = t.ToString();
		if (t < e) {
			answerText.text = T1.ToString();
			nextStepButton.interactable = false;
			return;
		}
		h /= 2;
		n *= 2;
		T0 = T1;
		T1 = 0;
		for (int k = 1; k < n; k++) {
			T1 += F(a + (k - 0.5f) * h);
		}
		T1 = T0 / 2f + h * T1 / 2f;
	}



	void GetData() {
		a = float.Parse(aInputField.text);
		b = float.Parse(bInputField.text);
		e = float.Parse(eInputField.text);
	}

	private float F(float x) {
		if (x == 0) return 0;
		return Mathf.Sin(x) / x * MainControler.Instance.yAxisMagnification;
	}

}
